<template>
  <div class="main_app">
    <h1>Hello</h1>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="form-container">
      <el-form-item label="公共脚本" prop="publicScript">
        <el-input v-model="form.publicScript" type="text" placeholder="请输入公共脚本"></el-input>
      </el-form-item>
      <el-form-item label="自定义脚本" prop="customScript">
        <el-input v-model="form.customScript" type="text" placeholder="请输入自定义脚本"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, watch } from 'vue'

const form = reactive({
  publicScript: '',
  customScript: ''
})
watch(() => form, () => {
  saveToStorage()
}, {
  deep: true
})
const formRef = ref(null)

const rules = reactive({
  publicScript: [
    { required: true, message: '请输入公共脚本', trigger: 'blur' }
  ],
  customScript: [
    { required: true, message: '请输入自定义脚本', trigger: 'blur' }
  ]
})

onMounted(() => {
  // 初始化时读取存储的数据
  chrome.storage.local.get(['publicScript', 'customScript'], (result) => {
    if (result.publicScript) form.publicScript = result.publicScript
    if (result.customScript) form.customScript = result.customScript
  })
})

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      alert('表单提交成功')
    } else {
      alert('表单校验失败，请检查输入')
      return false
    }
  })
}

const saveToStorage = () => {
  // 保存数据到Chrome存储
  chrome.storage.local.set({
    publicScript: form.publicScript,
    customScript: form.customScript
  })
}

defineOptions({
  name: 'app'
})
</script>

<style>
.main_app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  width: 580px;
  height: 580px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}
.form-container {
  width: 100%;
}
</style>
